<script setup>
import { ref, watch } from 'vue'
import useUserInfoStore from '@/stores/userInfo.js'
const userInfoStore = useUserInfoStore();

// 使用临时对象来存储表单数据
const tempUserInfo = ref({ ...userInfoStore.info });

const rules = {
    name: [
        { required: true, message: '请输入用户昵称', trigger: 'blur' },
        {
            pattern: /^\S{2,10}$/,
            message: '昵称必须是2-10位的非空字符串',
            trigger: 'blur'
        }
    ],
    description: [
        { required: true, message: '请输入个人信息描述', trigger: 'blur' },
        {
            pattern: /^\S{2,100}$/,
            message: '描述必须是2-100位的非空字符串',
            trigger: 'blur'
        }
    ]
}

// 修改个人信息
import { userInfoUpdateService } from '@/api/userApi/user.js'
import { ElMessage } from 'element-plus'
const updateUserInfo = async () => {
    // 调用接口
    let result = await userInfoUpdateService(tempUserInfo.value);
    ElMessage.success(result.msg ? result.msg : '修改成功');
    
    // 修改 Pinia 中的个人信息
    userInfoStore.setInfo(tempUserInfo.value);
}

// 监听 Pinia 中的 userInfo 变化，并更新 tempUserInfo
watch(() => userInfoStore.info, (newInfo) => {
    tempUserInfo.value = { ...newInfo };
}, { immediate: true });
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>基本资料</span>
            </div>
        </template>
        <el-row justify="center">
            <el-col :span="12">
                <el-form :model="tempUserInfo" :rules="rules" label-width="100px" size="large">
                    <el-form-item label="用户名">
                        <el-input v-model="tempUserInfo.username" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="tempUserInfo.name"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" prop="gender">
                        <el-select v-model="tempUserInfo.gender" placeholder="请选择性别">
                            <el-option label="男" value="男"></el-option>
                            <el-option label="女" value="女"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="信息描述" prop="info">
                        <el-input type="textarea" v-model="tempUserInfo.info"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="updateUserInfo">提交修改</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>